<template>
  <div>

    <div class="top-header" :style="{position:isFixed?'fixed':'sticky'}">
      <!-- 头部 -->
      <SearchBar :q="keyword" @query="doSearch"/>

      <!-- 过滤菜单 -->
      <ul class="filter-menu">
        <li :class="{active:activeIndex===index}"
            @click="changeIndex(index)"
            v-for="(item, index) in tabList"
            :key="index">{{item}}</li>
      </ul>
    </div>
     

    <!-- 商品列表 -->
    <ul class="goods-list">
      <li class="goods" v-for="(item, index) in goodsList" :key="index" @click="toItem(item.goods_id)">
        <img :src="item.goods_small_logo"
             alt="">
        <div class="right">
          <p class="goods-name text-line2">{{item.goods_name}}</p>
          <p class="price">￥<span>{{item.goods_price}}</span>.00</p>
        </div>
      </li>
    </ul>
    <p class="btm-line" v-show="isLastPage">--我是有底线的--</p>
  </div>
</template>
<script>
import SearchBar from '@/components/SearchBar'

const PAGE_SIZE = 6
export default {
  components: {
    SearchBar
  },
  data () {
    return {
      tabList: [
        '销量',
        '综合',
        '价格'
      ],
      activeIndex: 0,
      keyword: '',
      goodsList: [],
      // 是否在请求中
      // isRequest: false,
      // 默认不是最后一页
      isLastPage: false,
      isFixed: false
    }
  },
  onLoad (options) {
    // 声明Vue实例属性的变量
    // 是否在请求中
    // 清空goodsList,vue实例没有销毁
    this.isRequest = false
    this.keyword = options.catName
    this.reload()
  },
  onPullDownRefresh () {
    this.isFixed = false
    this.reload()
  },
  onPageScroll () {
    this.isFixed = true
  },
  onReachBottom () {
    // 加载下一页的数据
    // 页码+1，再发请求
    this.pageNum++
    this.queryGoodsList()
  },
  methods: {
		changeIndex(index){
			this.activeIndex=index
		},
    doSearch (data) {
      this.keyword = data
      this.reload()
    },
    toItem (goodsId) {
      wx.navigateTo({ url: '/pages/item/main?goodsId=' + goodsId })
    },
    reload () {
      // 搜索列表清空
      this.goodsList = []
      this.pageNum = 1
      this.isLastPage = false
      this.queryGoodsList()
    },
    async queryGoodsList () {
      // 如果请求中就不再发请求，或者是最后一页时
      if (this.isRequest || this.isLastPage) {
        return
      }
      // 在请求前，设置标志为请求中
      this.isRequest = true
      const data = await this.$request({
        url: '/api/public/v1/goods/search',
        data: {
          query: this.keyword,
          pagesize: PAGE_SIZE,
          pagenum: this.pageNum
        },
        noLoading: true
      })
      // 请求后，设置标志为请求完成，也就是不在请求中
      this.isRequest = false
      wx.stopPullDownRefresh()
      // 下一页的数据要追加
      this.goodsList = [...this.goodsList, ...data.goods]
      // 商品列表长度等于total时，已经到了最后一页
      if (data.total <= this.goodsList.length) {
        this.isLastPage = true
      }
    }
  }
}
</script>

<style lang="less">
@import url('./index.less');
</style>